package com.mytest.example.asyncservlet.config;

import com.mytest.example.asyncservlet.component.AsyncTaskFilter;
import com.mytest.example.asyncservlet.component.AsyncTaskInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AsyncTaskInterceptor()).addPathPatterns("/**");

    }

    /**
     * 配置异步默认线程池
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(100);
        //配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(200);
        //配置线程池前缀
        threadPoolTaskExecutor.setThreadNamePrefix("async-service-");
        threadPoolTaskExecutor.initialize();

        configurer.setTaskExecutor(threadPoolTaskExecutor);
    }

    @Bean
    public FilterRegistrationBean httpFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new AsyncTaskFilter());
        bean.setName("httpFilter");
        bean.addUrlPatterns("/*");//过滤所有路径
        bean.setOrder(1);//优先级，最顶级\
        bean.setAsyncSupported(true);
        return bean;
    }
}
